# -*- coding: utf-8 -*-
###################################################################################
#   
#    Copyright (C) 2019 RedTN 
# 
#此程序是自由软件：您可以根据自由软件基金会发布的GNU Affero通用公共许可证（许可证的第3版或（由您选择）任何更高版本）的条款重新分发和/或修改它。
#这个程序是分发的，希望它是有用的，但没有任何保证；甚至没有隐含的保证适销性或适合特定用途。有关详细信息，请参阅GNU Affero通用公共许可证。
#
#您应该已经收到GNU Affero通用公共许可证的副本以及此程序。如果没有，请参见<http://www.gnu.org/licenses/>。#
###################################################################################

import re
import logging

from lxml import etree

from odoo import _
from odoo import models, api, fields,_
from odoo.tools import html2plaintext
from odoo.exceptions import UserError, AccessError

_logger = logging.getLogger(__name__)

class Document(models.Model):
    
    _name = "hr_official_docs.document"
    _description = "Offic"
    _inherit = ["mail.thread", "mail.activity.mixin"]
    #_rec_name = "ref_and_name"
    
    #_access_groups_fields = None
    #_access_groups_strict = False
    #_access_groups_mode = True
    
    #===========================================================================
    # Variables
    #===========================================================================

    name = fields.Char(
        required=True,
        track_visibility="onchange",
        translate=True
    )
    
    partner_id = fields.Many2one(
        "res.users",
        string="Related Partner",
    )
    
    stage_id = fields.Many2one(
        "hr_official_docs.userstage",
        string="Stage",
        ondelete="RESTRICT",
        index=True,
        readonly=True,
        force_save=True,
        track_visibility="onchange"
    )

    prev_stage_name = fields.Char(
        compute="_compute_stage_names"
    )

    next_stage_name = fields.Char(
        compute="_compute_stage_names"
    )

    has_right_for_prev_stage = fields.Boolean(
        compute="_compute_has_right_for_prev_stage"
    )
    
    has_right_for_next_stage = fields.Boolean(
        compute="_compute_has_right_for_next_stage"
    )
    
    description = fields.Html(
        string='Description', 
        translate=True
    )
    
    summary = fields.Text(
        compute='_compute_summary', 
        string='Summary', 
        store=True)
    

    template_id = fields.Many2one(
        "hr_official_docs.usertemplate",
        "Template",
        required=True,
    )
    
    attachment_id_1 = fields.Many2many('ir.attachment', 'offic_docs_rel_1', string="Attachment")

    active = fields.Boolean(default=True)

    
    #===========================================================================
    # View Functions
    #===========================================================================
    
    @api.model
    def fields_view_get(self, view_id=None, view_type='form', toolbar=False, submenu=False):
        # This is needed since tree view wont validate with a js_class attribute
        res = super(Document, self).fields_view_get(view_id, view_type, toolbar, submenu)
        if view_type == 'tree':
            doc = etree.fromstring(res['arch'])
            tree = next(iter( doc.xpath("//tree") or []), None)
            if len(tree):
                tree.set("js_class", "offic_document_list")
                res['arch'] = etree.tostring(doc, encoding='unicode')
        return res
        
    #===========================================================================
    # Computed Functions
    #===========================================================================

    @api.depends('stage_id')
    def _compute_stage_names(self):
        for record in self:
            record.update({
                'prev_stage_name': record.stage_id.prev_stage_id.name,
                'next_stage_name': record.stage_id.next_stage_id.name})
    
    @api.depends('description')
    def _compute_summary(self):
        for record in self:
            text = html2plaintext(record.description) if record.description else ''
            record.summary = text.strip().replace('*', '').split("\n")[0]
            

    #@api.onchange('stage_id')    #guo
    def _compute_has_right_for_prev_stage(self):
        for record in self:
            stage_new = record.stage_id.prev_stage_id
            
            has_right = False
            
            if stage_new:
                get_param = self.env["ir.config_parameter"].sudo().get_param
                enable_workflow_prev_stage = get_param("hr_official_docs.enable_workflow_prev_stage")
                has_group = self.env.user.has_group("hr_official_docs.group_hr_official_docs_manager")
                if enable_workflow_prev_stage and has_group:
                    has_right = True
                elif enable_workflow_prev_stage and self.env.user in record.stage_id.operator: ##guo
                    has_right = True
                    
            record.has_right_for_prev_stage = has_right
                
    #@api.onchange('stage_id')       #guo 
    def _compute_has_right_for_next_stage(self):
        for record in self:
            stage_new = record.stage_id.next_stage_id
            
            has_right = False
            
            if stage_new:
                if self.env.user.has_group("hr_official_docs.group_hr_official_docs_manager"):
                    has_right = True
                elif self.env.user in record.stage_id.operator: ##guo
                    has_right = True
                    
            record.has_right_for_next_stage = has_right
                
    #===========================================================================
    # Worfklow Functions
    #===========================================================================
    
    
    def set_stage_to_next(self):
        for record in self:
        
            if not record.has_right_for_next_stage:
                msg = "You are not allowed to change to the next workflow stage."
                _logger.exception(msg)
                raise UserError(_(msg))
            
            stage_new = record.stage_id.next_stage_id
            
            if not stage_new:
                msg = "This is already the last stage."
                _logger.exception(msg)
                raise UserError(_(msg))

            #record.stage_id.sudo().write({"iscompleted":True})
            record.write({
                "stage_id": stage_new.id,
            })
        
    
    def set_stage_to_prev(self):
        for record in self:
            
            if not record.has_right_for_prev_stage:
                msg = "You are not allowed to change to the previous workflow stage."
                _logger.exception(msg)
                raise UserError(_(msg))
            
            stage_new = record.stage_id.prev_stage_id
            
            if not stage_new:
                msg = "This is already the first stage."
                _logger.exception(msg)
                raise UserError(_(msg))
            
            #if record.stage_id.iscompleted:
                #record.stage_id.sudo().write({"iscompleted":False})
            record.write({
                "stage_id": stage_new.id,
            })
            #record.stage_id.sudo().write({"iscompleted":False})

    #===========================================================================
    # ORM Functions
    #===========================================================================
    
    @api.model
    def create(self, values):

        if values['template_id']:    #guo
            stage = self.env["hr_official_docs.userstage"].get_first_stage(values['template_id'])\

            if not stage:
                raise UserError(_('You must set stages in user template!'))
            values['stage_id'] =  stage.id         ##guo

        record = super(Document, self).create(values)
        
        if record.template_id:
            record.with_context({}).post_create_document_from_template()
            
        return record
    
    #===========================================================================
    # Helper Functions
    #===========================================================================
    
    def _get_document_context(self):
        context = {
            "form_view_initial_mode": "edit",
            "force_detailed_view": True,
            "default_template_document_id": self.id,
        }
        
        if self.name:
            context.update({"default_name": self.name})
        
        if self.description:
            context.update({"default_description": self.description})
            
        return context
    
    #===========================================================================
    # View Actions
    #===========================================================================
        
    def action_create_document_from_document(self):
        context = self._get_document_context()
        
        return {
            "name": _("Create New Document"),
            "type": "ir.actions.act_window",
            "view_mode": "form",
            "res_model": "hr_official_docs.document",
            "target": "current",
            "context": context
        }

    def action_toggle_active(self):
        if self.active :
            self.active = False
        else:
            self.active = True


    @api.onchange('template_id')
    def action_get_stage_from_template(self):
        #context = self._get_document_context()

        self.description=self.template_id.document_description
        return {
          'domain': {'stage_id': [('template_id','=',self.template_id.id),('create_uid','=',self.env.user.id),('operator','!=',False)]}
        }

    #===========================================================================
    # Post Create Document Functions
    #===========================================================================

    def post_create_document_from_template(self):
        _logger.info("Template[id={}]: Document[id={}] created.".format(self.template_id.id, self.id))
        return self
